# -*- coding: utf-8 -*-
# flake8: noqa

from qiniu import Auth, put_file, etag
import qiniu.config
import requests
import os
import time, hashlib
import random, string
import sys
import cStringIO, urllib2
import uuid
import shortuuid
import tinify
from PIL import Image as image
from fileManage import clean


#七牛的配置信息
baseUrl = 'http://images.samecity.com.cn/'
access_key = '9ylMDpP1TSRD9Al2jAnaV099Q6Y-WuZmgR3HbD_s'
secret_key = 'HGgEnOGOpc_7SMTVZlcv56EOlECYMOzoPX6jR_it'
bucket_name = 'jigu-app'


# 等比例压缩图片
def resizeImg(**args):
    args_key = {'ori_img': '', 'dst_img': '', 'dst_w': '', 'dst_h': '', 'save_q': 75}
    arg = {}
    for key in args_key:
        if key in args:
            arg[key] = args[key]

    im = image.open(arg['ori_img'])
    ori_w, ori_h = im.size
    widthRatio = heightRatio = None
    ratio = 1
    if (ori_w and ori_w > arg['dst_w']) or (ori_h and ori_h > arg['dst_h']):
        if arg['dst_w'] and ori_w > arg['dst_w']:
            widthRatio = float(arg['dst_w']) / ori_w  # 正确获取小数的方式
        if arg['dst_h'] and ori_h > arg['dst_h']:
            heightRatio = float(arg['dst_h']) / ori_h

        if widthRatio and heightRatio:
            if widthRatio < heightRatio:
                ratio = widthRatio
            else:
                ratio = heightRatio

        if widthRatio and not heightRatio:
            ratio = widthRatio
        if heightRatio and not widthRatio:
            ratio = heightRatio

        newWidth = int(ori_w * ratio)
        newHeight = int(ori_h * ratio)
    else:
        newWidth = ori_w
        newHeight = ori_h

    im.resize((newWidth, newHeight), image.ANTIALIAS).save(arg['dst_img'], quality=arg['save_q'])

#清除图片
def cleanFile():
    localPath = sys.path[0] + '/wechatsogou/wxspider/'
    file1 = clean(localPath)
    file1.delfile()

#上传到熊猫压缩图片
def compress(filename):
    try:
        source = tinify.from_file(filename)
        source.to_file(filename)
        print 'yes'
        return 'yes'
    except Exception:
        return 'no'

#生成图片文件名
def uploadImage(imageUrl, width):

    q = Auth(access_key, secret_key)
    randomStr = shortuuid.ShortUUID().random(length=32) + str(time.time()).replace('.', '')
    imgKey = randomStr
    filename = os.path.basename(imageUrl)
    print filename

    #判断图片的后缀
    if filename.find('gif') >= 2:
        filename = imgKey + '.gif'
    elif filename.find('jpg') >= 2:
        filename = imgKey + '.jpg'
    elif filename.find('png') >= 2:
        filename = imgKey + '.png'
    else:
        filename = imgKey + '.jpeg'

    #七牛的文件名
    bigfilename = 'wxspider/' + filename
    #保存图片的绝对路径
    localBigfiles = sys.path[0] + '/wechatsogou/' + bigfilename
    print localBigfiles

    img = requests.get(imageUrl)
    # 写入流
    with open(localBigfiles, 'wb') as f:
        f.write(img.content)
        #获取图片的大小
        # imgSize = os.stat(localBigfiles).st_size
        imgName = str(filename).split('.')[1]

        if imgName != 'gif':
            token = q.upload_token(bucket_name, bigfilename, 3600)
            info = put_file(token, bigfilename, localBigfiles)
            if info[1].status_code == 200:
                print('upload big picture success： ', info[1].status_code)
                cleanFile()
                return baseUrl + bigfilename
            else:
                print('upload big picture fail：', info)
                return ''
        else:
            token = q.upload_token(bucket_name, bigfilename, 3600)
            info = put_file(token, bigfilename, localBigfiles)
            if info[1].status_code == 200:
                print('upload big picture success： ', info[1].status_code)
                cleanFile()
                return baseUrl + bigfilename
            else:
                print('upload big picture fail：', info)
                return ''
